import React, { useState, useEffect } from 'react';
import axios from 'axios';
import styles from './Todo.module.css';

function App() {
  // 状态管理
  const [todos, setTodos] = useState([]);
  const [showDialog, setShowDialog] = useState(false);
  const [dialogMode, setDialogMode] = useState('add');
  const [currentTodoId, setCurrentTodoId] = useState(null);
  const [newTodo, setNewTodo] = useState({
    title: '',
    tags: '工作',
    remark: '',
    priority: '中'
  });
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [todosPerPage, setTodosPerPage] = useState(3);
  
  // 获取待办事项
  useEffect(() => {
    const fetchTodos = async () => {
      try {
        const res = await axios.get('http://localhost:3001/todos');
        setTodos(res.data);
      } catch (err) {
        console.error('获取待办事项失败:', err);
      }
    };
    fetchTodos();
  }, []);

  // 添加/编辑待办事项对话框
  const openDialog = (mode = 'add', todo = null) => {
    setDialogMode(mode);
    if (mode === 'edit' && todo) {
      setCurrentTodoId(todo.id);
      setNewTodo({
        title: todo.title,
        tags: todo.tags,
        remark: todo.remark,
        priority: todo.priority
      });
    } else {
      setCurrentTodoId(null);
      setNewTodo({
        title: '',
        tags: '工作',
        remark: '',
        priority: '中'
      });
    }
    setShowDialog(true);
  };

  // 添加/更新待办事项
  const handleSubmitTodo = async (e) => {
    e.preventDefault();
    try {
      if (dialogMode === 'add') {
        const res = await axios.post('http://localhost:3001/todos', {
          ...newTodo,
          status: '未完成',
          date: new Date().toISOString().split('T')[0],
          completed: false
        });
        setTodos([...todos, res.data]);
      } else {
        const todoToUpdate = todos.find(todo => todo.id === currentTodoId);
        const updatedTodo = {
          ...todoToUpdate,
          ...newTodo
        };
        
        await axios.put(`http://localhost:3001/todos/${currentTodoId}`, updatedTodo);
        setTodos(todos.map(todo => todo.id === currentTodoId ? updatedTodo : todo));
      }
      
      setShowDialog(false);
      setNewTodo({
        title: '',
        tags: '工作',
        remark: '',
        priority: '中'
      });
      setCurrentPage(1);
    } catch (err) {
      console.error(dialogMode === 'add' ? '添加' : '更新', '待办事项失败:', err);
    }
  };

  // 切换待办状态
  const toggleTodoStatus = async (id) => {
    try {
      const todoToUpdate = todos.find(todo => todo.id === id);
      const updatedTodo = {
        ...todoToUpdate,
        completed: !todoToUpdate.completed,
        status: todoToUpdate.completed ? '未完成' : '已完成'
      };
      
      await axios.put(`http://localhost:3001/todos/${id}`, updatedTodo);
      setTodos(todos.map(todo => todo.id === id ? updatedTodo : todo));
    } catch (err) {
      console.error('更新待办事项失败:', err);
    }
  };

  // 删除待办事项
  const handleDeleteTodo = async (id) => {
    try {
      await axios.delete(`http://localhost:3001/todos/${id}`);
      setTodos(todos.filter(todo => todo.id !== id));
      const newFiltered = todos.filter(todo => 
        todo.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        todo.tags.toLowerCase().includes(searchTerm.toLowerCase())
      );
      const newTotalPages = Math.ceil(newFiltered.length / todosPerPage);
      if (currentPage > newTotalPages && newTotalPages > 0) {
        setCurrentPage(newTotalPages);
      }
    } catch (err) {
      console.error('删除待办事项失败:', err);
    }
  };

  // 搜索和分页逻辑
  const filteredTodos = todos.filter(todo =>
    todo.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
    todo.tags.toLowerCase().includes(searchTerm.toLowerCase())
  );

  const indexOfLastTodo = currentPage * todosPerPage;
  const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
  const currentTodos = filteredTodos.slice(indexOfFirstTodo, indexOfLastTodo);
  const totalPages = Math.ceil(filteredTodos.length / todosPerPage);

  const paginate = (pageNumber) => setCurrentPage(pageNumber);
  
  // 生成页码数组
  const getPageNumbers = () => {
    const pageNumbers = [];
    const maxVisiblePages = 5;
    
    if (totalPages <= maxVisiblePages) {
      for (let i = 1; i <= totalPages; i++) {
        pageNumbers.push(i);
      }
    } else {
      let startPage = Math.max(1, currentPage - 2);
      let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
      
      if (endPage - startPage < maxVisiblePages - 1) {
        startPage = endPage - maxVisiblePages + 1;
      }
      
      if (startPage > 1) {
        pageNumbers.push(1);
        if (startPage > 2) {
          pageNumbers.push('...');
        }
      }
      
      for (let i = startPage; i <= endPage; i++) {
        pageNumbers.push(i);
      }
      
      if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
          pageNumbers.push('...');
        }
        pageNumbers.push(totalPages);
      }
    }
    
    return pageNumbers;
  };

  return (
    <div className={styles.appContainer}>
      {/* 左侧导航栏 */}
      <div className={styles.sidebar}>
        <button 
          className={styles.addBtn}
          onClick={() => openDialog('add')}
        >
          添加待办事项
        </button>
        
        <div className={styles.sidebarSection}>
          <div className={styles.sidebarTitle}>
            <i className="icon-filter"></i> 筛选
          </div>
          <div className={styles.sidebarItem}>
            <i className="icon-tag"></i>
            <span>标记</span>
          </div>
          <div className={styles.sidebarItem}>
            <i className="icon-star"></i>
            <span>优先</span>
          </div>
          <div className={styles.sidebarItem}>
            <i className="icon-calendar"></i>
            <span>预约</span>
          </div>
          <div className={styles.sidebarItem}>
            <i className="icon-today"></i>
            <span>今天</span>
          </div>
          <div className={styles.sidebarItem}>
            <i className="icon-check"></i>
            <span>完成</span>
          </div>
          <div className={styles.sidebarItem}>
            <i className="icon-trash"></i>
            <span>删除</span>
          </div>
        </div>

        <div className={styles.sidebarSection}>
          <div className={styles.sidebarTitle}>
            <i className="icon-tags"></i> 标签
          </div>
          <div className={styles.tagItem}>
            <span className={`${styles.tagCircle} ${styles.tagCircleSocial}`}></span>
            <span>社交</span>
          </div>
          <div className={styles.tagItem}>
            <span className={`${styles.tagCircle} ${styles.tagCirclePersonal}`}></span>
            <span>个人</span>
          </div>
          <div className={styles.tagItem}>
            <span className={`${styles.tagCircle} ${styles.tagCircleClient}`}></span>
            <span>客户</span>
          </div>
          <div className={styles.tagItem}>
            <span className={`${styles.tagCircle} ${styles.tagCircleEvent}`}></span>
            <span>事件</span>
          </div>
          <div className={styles.tagItem}>
            <span className={`${styles.tagCircle} ${styles.tagCircleWork}`}></span>
            <span>工作</span>
          </div>
        </div>
      </div>

      {/* 右侧内容区 */}
      <div className={styles.content}>
        {/* 对话框 */}
        {showDialog && (
          <div className={styles.dialogContainer}>
            <div className={styles.dialogOverlay} onClick={() => setShowDialog(false)}></div>
            <div className={styles.dialogContent}>
              <div className={styles.dialog}>
                <h3>{dialogMode === 'add' ? '添加新待办' : '编辑待办事项'}</h3>
                <form onSubmit={handleSubmitTodo}>
                  <div className={styles.formGroup}>
                    <label>标题</label>
                    <input
                      type="text"
                      value={newTodo.title}
                      onChange={(e) => setNewTodo({...newTodo, title: e.target.value})}
                      required
                      placeholder="请输入待办事项标题"
                    />
                  </div>
                  
                  <div className={styles.formGroup}>
                    <label>标签</label>
                    <select
                      value={newTodo.tags}
                      onChange={(e) => setNewTodo({...newTodo, tags: e.target.value})}
                    >
                      <option value="工作">工作</option>
                      <option value="个人">个人</option>
                      <option value="家庭">家庭</option>
                      <option value="学习">学习</option>
                    </select>
                  </div>
                  
                  <div className={styles.formGroup}>
                    <label>优先级</label>
                    <select
                      value={newTodo.priority}
                      onChange={(e) => setNewTodo({...newTodo, priority: e.target.value})}
                    >
                      <option value="高">高</option>
                      <option value="中">中</option>
                      <option value="低">低</option>
                    </select>
                  </div>
                  
                  <div className={styles.formGroup}>
                    <label>备注</label>
                    <textarea
                      value={newTodo.remark}
                      onChange={(e) => setNewTodo({...newTodo, remark: e.target.value})}
                      placeholder="可选备注信息..."
                    />
                  </div>
                  
                  <div className={styles.dialogButtons}>
                    <button type="button" onClick={() => setShowDialog(false)}>
                      取消
                    </button>
                    <button type="submit">{dialogMode === 'add' ? '添加' : '更新'}</button>
                  </div>
                </form>
              </div>
            </div>
          </div>
        )}

        {/* 搜索框 */}
        <div className={styles.searchBar}>
          <input
            type="text"
            placeholder="搜索待办事项..."
            value={searchTerm}
            onChange={(e) => {
              setSearchTerm(e.target.value);
              setCurrentPage(1);
            }}
          />
        </div>

        {/* 待办事项表格 */}
        <table className={styles.todoTable}>
          <thead>
            <tr>
              <th width="5%" className={styles.th}>{'#'}</th>
              <th width="20%" className={styles.th}>标题</th>
              <th width="15%" className={styles.th}>标签</th>
              <th width="15%" className={styles.th}>优先级</th>
              <th width="25%" className={styles.th}>备注</th>
              <th width="10%" className={styles.th}>状态</th>
              <th width="10%" className={styles.th}>操作</th>
            </tr>
          </thead>
          <tbody>
            {currentTodos.length > 0 ? (
              currentTodos.map((todo, index) => (
                <tr key={todo.id}>
                  <td className={styles.td}>
                    <input
                      type="checkbox"
                      checked={todo.completed}
                      onChange={() => toggleTodoStatus(todo.id)}
                    />
                  </td>
                  <td className={styles.td} data-label="标题">{todo.title}</td>
                  <td className={styles.td} data-label="标签">{todo.tags}</td>
                  <td className={styles.td} data-label="优先级">{todo.priority}</td>
                  <td className={styles.td} data-label="备注">{todo.remark}</td>
                  <td className={styles.td} data-label="状态">
                    <span className={`${styles.status} ${todo.completed ? styles.statusCompleted : ''}`}>
                      {todo.status}
                    </span>
                  </td>
                  <td className={styles.td} data-label="操作">
                    <div className={styles.actionButtons}>
                      <button
                        className={styles.editBtn}
                        onClick={() => openDialog('edit', todo)}
                      >
                        编辑
                      </button>
                      <button
                        className={styles.deleteBtn}
                        onClick={() => handleDeleteTodo(todo.id)}
                      >
                        删除
                      </button>
                    </div>
                  </td>
                </tr>
              ))
            ) : (
              <tr>
                <td colSpan="7" className={styles.noTodos}>
                  没有找到待办事项
                </td>
              </tr>
            )}
          </tbody>
        </table>

        {/* 分页控件 */}
        {filteredTodos.length > 0 && (
          <div className={styles.paginationContainer}>
            <div className={styles.paginationInfo}>
              显示 {indexOfFirstTodo + 1} 至 {Math.min(indexOfLastTodo, filteredTodos.length)} 条，
              共 {filteredTodos.length} 条
            </div>
            <div className={styles.paginationSettings}>
              <div className={styles.perPageSelector}>
                <span>每页显示：</span>
                <select
                  value={todosPerPage}
                  onChange={(e) => {
                    setTodosPerPage(Number(e.target.value));
                    setCurrentPage(1);
                  }}
                >
                  <option value="3">3</option>
                  <option value="5">5</option>
                  <option value="10">10</option>
                  <option value="20">20</option>
                </select>
              </div>
              <div className={styles.paginationControls}>
                <button
                  onClick={() => paginate(currentPage > 1 ? currentPage - 1 : 1)}
                  disabled={currentPage === 1}
                  className={styles.pageBtn}
                >
                  上一页
                </button>
                
                {getPageNumbers().map((number, index) => (
                  number === '...' ? (
                    <span key={`ellipsis-${index}`} className={styles.ellipsis}>...</span>
                  ) : (
                    <button
                      key={number}
                      onClick={() => paginate(number)}
                      className={`${styles.pageBtn} ${currentPage === number ? styles.pageBtnActive : ''}`}
                    >
                      {number}
                    </button>
                  )
                ))}
                
                <button
                  onClick={() => paginate(currentPage < totalPages ? currentPage + 1 : totalPages)}
                  disabled={currentPage === totalPages}
                  className={styles.pageBtn}
                >
                  下一页
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

export default App;    